package com.leyou.auth.interceptors;

import com.leyou.auth.dto.Payload;
import com.leyou.auth.dto.UserDetail;
import com.leyou.auth.utils.JwtUtils;
import com.leyou.auth.utils.UserContext;
import com.leyou.common.exception.LyException;
import com.leyou.common.utils.CookieUtils;
import io.jsonwebtoken.JwtException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


@Slf4j
public class LoginInterceptor implements HandlerInterceptor {


    private final JwtUtils jwtUtils;

    public LoginInterceptor(JwtUtils jwtUtils) {
        this.jwtUtils = jwtUtils;
    }


    /**
     * 拦截器前置方法，返回false表示拦截，返回true表示放行
     *
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        try {
            // 获取cookie中的jwt
            String jwt = CookieUtils.getCookieValue(request, "LY_TOKEN");
            // 验证并解析
            Payload payload = jwtUtils.parseJwt(jwt);
            // 获取用户
            UserDetail userDetail = payload.getUserDetail();

            // 保存用户
            UserContext.setUser(userDetail);
            log.info("用户{}正在访问。", userDetail.getUsername());
            return true;
        } catch (JwtException e) {
            //同时删除无效的token

            Cookie cookie = new Cookie("LY_TOKEN","");
            cookie.setDomain("leyou.com");
            cookie.setPath("/");
            cookie.setMaxAge(0);
            response.addCookie(cookie);


            throw new LyException(401, "JWT无效或过期!", e);
        } catch (IllegalArgumentException e) {
            throw new LyException(401, "用户未登录!", e);
        }
    }


    /**
     * 最终处理
     *
     * @param request
     * @param response
     * @param handler
     * @param ex
     * @throws Exception
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

        //清理threadLocal中存储的内容
        UserContext.removeUser();
    }

    public static UserDetail getUserDetail() {
        return UserContext.getUser();
    }
}
